﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace Adjunct.Framework.Releases
{
	public class ReleaseNotes
	{
		private static readonly Regex Pattern = new Regex(SemanticVersion.Pattern);

		private readonly List<ReleaseNote> _releaseNotes = new List<ReleaseNote>();

		public int Count
		{
			get { return _releaseNotes.Count; }
		}

		public ReleaseNote this[string version]
		{
			get { return _releaseNotes.FirstOrDefault(n => n.Version == version); }
		}

		public void Add(ReleaseNote note)
		{
			_releaseNotes.Add(note);
		}

		public static ReleaseNotes Load(string path)
		{
			ReleaseNotes notes = new ReleaseNotes();
			//ToDo: support xml format(s)
			string contents;
			using (StreamReader reader = File.OpenText(path))
			{
				contents = reader.ReadToEnd();
			}
			MatchCollection matches = Pattern.Matches(contents);
			for (int i = 0; i < matches.Count; i++)
			{
				Match match = matches[i];
				int textStart = match.Index + match.Length;
				if (i + 1 == matches.Count)
				{
					notes.Add(new ReleaseNote {Version = match.Value, Text = contents.Substring(textStart).Trim()});
				}
				else
				{
					notes.Add(new ReleaseNote {Version = match.Value, Text = contents.Substring(textStart, matches[i + 1].Index - textStart)});
				}
			}
			return notes;
		}
	}
}